package choreganizer;

import java.io.*;
import java.util.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.xml.sax.*;
import org.xml.sax.helpers.*; 

import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;



public class MyWriters
{
	private static String newLine = "\n";
	private File databaseFile;
	
	
	
	public MyWriters(File databaseFile)
	{
		this.databaseFile = databaseFile;
	}
	
	// Create xml data from the ChoreData files
	public String getChoreData(ChoreData[] choreList)
	{
		StringBuilder sb = new StringBuilder();
			
		sb.append( "<?xml version='1.0' encoding='utf-8'?>" + newLine );
		sb.append( "<chores>" + newLine + newLine);
		for (ChoreData cd: choreList)
			sb.append( cd.toXMLString() + newLine );
		sb.append( "</chores>" + newLine );
		
		return sb.toString();
	}
	
	// Create xml data from the ScheduleData files
	public String getScheduleData(ScheduleData[] schedList)
	{
		StringBuilder sb = new StringBuilder();
			
		sb.append( "<?xml version='1.0' encoding='utf-8'?>" + newLine );
		sb.append( "<schedules>" + newLine + newLine);
		for (ScheduleData sd: schedList)
			sb.append( sd.toXMLString() + newLine );
		sb.append( "</schedules>" + newLine );
		
		return sb.toString();
	}
	
	// Write the arrays to the zip file
	public void writeToDatabase(ChoreData[] choreList, ScheduleData[] schedList)
	{
		ZipOutputStream zout = null;
		FileOutputStream fout = null;
		try
		{
			// Create streams into our zip database file
			fout = new FileOutputStream( databaseFile );
			zout = new ZipOutputStream( fout );
			
			// Write the chore file to the zip
			zout.putNextEntry(new ZipEntry("chores.xml"));
			String choreData = getChoreData( choreList );
			zout.write( choreData.getBytes() );
			zout.closeEntry();
			
			// Write the schedule file to our zip
			zout.putNextEntry(new ZipEntry("schedules.xml"));
			String schedData = getScheduleData( schedList );
			zout.write( schedData.getBytes() );
			zout.closeEntry();
			
			// Cleanup
			choreData = null;
			schedData = null;
		}
		catch (Exception e)
		{
			System.out.println("Error in MyWriters.writeToDatabase()");
			System.err.println( e );
		}
		// Make sure to close our streams regardless of what happens
		finally
		{
			try {
				if (zout != null)
				{
					zout.close();
					zout = null;
				}
				if (fout != null)
				{
					fout.close();
					fout = null;
				}
			} catch (Exception ex) {
				//
			}
		}
	}
}
